<template>
  <div class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50 transition-all duration-300" :class="{ shadow: isScrolled }">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <div class="flex items-center">
            <a href="#" class="flex items-center space-x-2">
              <div class="w-8 h-8 bg-gradient-primary rounded-lg flex items-center justify-center">
                <i class="fa fa-user-plus text-white"></i>
              </div>
              <span class="text-xl font-bold text-primary">账户注册</span>
            </a>
          </div>
          <div class="md:hidden">
            <button type="button" class="text-gray-600 hover:text-primary">
              <i class="fa fa-bars text-xl"></i>
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 sm:px-6 lg:px-8 py-8 md:py-16">
      <div class="max-w-6xl mx-auto">
        <div class="flex flex-col md:flex-row items-center gap-8 lg:gap-16">
          <!-- 左侧说明区域 -->
          <div class="space-y-8">
            <div>
              <h2 class="text-4xl font-bold text-gray-900 leading-tight">
                简单三步，<br>
                <span class="text-blue-500">快速注册</span>
              </h2>
              <p class="mt-4 text-gray-600 max-w-md">
                只需提供用户名、邮箱和密码，即可完成注册，开始您的体验之旅。
              </p>
            </div>

            <div class="space-y-6">
              <!-- 步骤1 -->
              <div class="flex items-start">
                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 mr-4">
                  <i class="fa fa-user"></i>
                </div>
                <div>
                  <h3 class="text-lg font-medium text-gray-900">创建个人资料</h3>
                  <p class="mt-1 text-gray-600">设置您的用户名，这将是您在平台上的标识</p>
                </div>
              </div>

              <!-- 步骤2 -->
              <div class="flex items-start">
                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 mr-4">
                  <i class="fa fa-envelope"></i>
                </div>
                <div>
                  <h3 class="text-lg font-medium text-gray-900">验证邮箱</h3>
                  <p class="mt-1 text-gray-600">我们会发送验证链接到您的邮箱，确保账户安全</p>
                </div>
              </div>

              <!-- 步骤3 -->
              <div class="flex items-start">
                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 mr-4">
                  <i class="fa fa-lock"></i>
                </div>
                <div>
                  <h3 class="text-lg font-medium text-gray-900">设置密码</h3>
                  <p class="mt-1 text-gray-600">创建安全密码，保护您的账户信息</p>
                </div>
              </div>
            </div>

            <div class="pt-2">
              <p class="text-gray-600">已有账户？
                <a href="/login" @click.prevent="router.push('/login')" class="text-blue-500 hover:underline font-medium">立即登录</a>
              </p>
            </div>
          </div>

          <!-- 右侧注册表单 -->
          <div class="md:w-5/12 w-full">
            <div class="bg-white rounded-2xl shadow-card p-6 md:p-8 transform transition-all duration-300 hover:shadow-lg">
              <h2 class="text-2xl font-bold mb-6 text-center">创建新账户</h2>

              <form @submit.prevent="handleSubmit" class="space-y-5">
                <!-- 用户名 -->
                <div class="space-y-2">
                  <label for="account" class="block text-sm font-medium text-gray-700">用户名</label>
                  <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <i class="fa fa-user text-gray-400"></i>
                    </div>
                    <input
                        type="text"
                        id="account"
                        v-model.trim="formData.account"
                        @input="validateAccount"
                        class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300 shadow-input"
                        placeholder="请输入用户名"
                        required
                    >
                    <div v-if="accountValid" class="absolute inset-y-0 right-0 pr-3 flex items-center text-green-500">
                      <i class="fa fa-check-circle"></i>
                    </div>
                    <div v-if="!accountValid && accountTouched" class="absolute inset-y-0 right-0 pr-3 flex items-center text-red-500">
                      <i class="fa fa-exclamation-circle"></i>
                    </div>
                  </div>
                  <p v-if="!accountValid && accountTouched" class="text-sm text-red-600">{{ accountError }}</p>
                </div>

                <!-- 邮箱 -->
                <div class="space-y-2">
                  <label for="email" class="block text-sm font-medium text-gray-700">邮箱地址</label>
                  <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <i class="fa fa-envelope text-gray-400"></i>
                    </div>
                    <input
                        type="email"
                        id="email"
                        v-model.trim="formData.email"
                        @input="validateEmail"
                        class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300 shadow-input"
                        placeholder="请输入邮箱地址"
                        required
                    >
                    <div v-if="emailValid" class="absolute inset-y-0 right-0 pr-3 flex items-center text-green-500">
                      <i class="fa fa-check-circle"></i>
                    </div>
                    <div v-if="!emailValid && emailTouched" class="absolute inset-y-0 right-0 pr-3 flex items-center text-red-500">
                      <i class="fa fa-exclamation-circle"></i>
                    </div>
                  </div>
                  <p v-if="!emailValid && emailTouched" class="text-sm text-red-600">{{ emailError }}</p>
                </div>

                <!-- 密码 -->
                <div class="space-y-2">
                  <div class="flex justify-between">
                    <label for="password" class="block text-sm font-medium text-gray-700">设置密码</label>
                    <span class="text-xs text-gray-500">密码强度: {{ passwordStrengthText }}</span>
                  </div>
                  <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <i class="fa fa-lock text-gray-400"></i>
                    </div>
                    <input
                        :type="showPassword ? 'text' : 'password'"
                        id="password"
                        v-model="formData.password"
                        @input="validatePassword"
                        class="w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all-300 shadow-input"
                        placeholder="请设置密码"
                        required
                    >
                    <button
                        type="button"
                        @click="togglePasswordVisibility"
                        class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
                    >
                      <i :class="showPassword ? 'fa fa-eye' : 'fa fa-eye-slash'"></i>
                    </button>
                  </div>
                  <div class="w-full bg-gray-200 rounded-full h-1.5">
                    <div
                        :style="{ width: passwordStrength + '%' }"
                        :class="passwordStrengthClass"
                        class="h-1.5 rounded-full transition-all duration-300"
                    ></div>
                  </div>
                  <p class="text-xs text-gray-500">密码至少8位，包含字母和数字</p>
                  <p v-if="!passwordValid && passwordTouched" class="text-sm text-red-600">{{ passwordError }}</p>
                </div>

                <!-- 注册按钮 -->
                <div>
                  <div>
                    <button
                        type="submit"
                        :disabled="isSubmitting"
                        class="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium py-2.5 px-4 rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-70 disabled:cursor-not-allowed"
                    >
                      <span v-if="!isSubmitting">注册账户</span>
                      <span v-if="isSubmitting">注册中...</span>
                    </button>
                  </div>
                </div>

                <!-- 条款协议 -->
                <div class="text-center">
                  <p class="text-xs text-gray-500">
                    点击"注册账户"，即表示您同意我们的
                    <a href="#" class="text-primary hover:underline">服务条款</a>
                    和
                    <a href="#" class="text-primary hover:underline">隐私政策</a>
                  </p>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-8">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col md:flex-row justify-between items-center">
          <div class="mb-4 md:mb-0">
            <p class="text-gray-500 text-sm">&copy; 2023 账户注册平台. 保留所有权利.</p>
          </div>
          <div class="flex space-x-6">
            <a href="#" class="text-gray-500 hover:text-primary transition-colors">
              <i class="fa fa-question-circle"></i> 帮助中心
            </a>
            <a href="#" class="text-gray-500 hover:text-primary transition-colors">
              <i class="fa fa-shield"></i> 隐私政策
            </a>
            <a href="#" class="text-gray-500 hover:text-primary transition-colors">
              <i class="fa fa-file-text"></i> 服务条款
            </a>
          </div>
        </div>
      </div>
    </footer>

    <!-- 注册成功弹窗 -->
    <div
        id="successModal"
        class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 transition-opacity duration-300"
        :class="{ hidden: !showSuccessModal, 'opacity-100': showSuccessModal }"
        @click="closeModal"
    >
      <div
          class="bg-white rounded-xl p-6 max-w-md w-full mx-4 transform transition-transform duration-300"
          :class="{ 'scale-100': showSuccessModal, 'scale-95': !showSuccessModal }"
          @click.stop
      >
        <div class="text-center">
          <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <i class="fa fa-check text-2xl text-green-500"></i>
          </div>
          <h3 class="text-xl font-bold mb-2">注册成功！</h3>
          <p class="text-gray-600 mb-6">我们已向您的邮箱发送了验证链接，请查收并完成验证。</p>
<!--          <button-->
<!--              @click="closeModal"-->
<!--              class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-all-300"-->
<!--          >-->
<!--            确定-->
<!--          </button>-->
          <button
              @click="goToLogin"
              class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-6 rounded-lg transition-all-300"
          >
            立即登录
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
// 表单数据
const formData = reactive({
  account: '',
  email: '',
  password: ''
});
// 表单提交处理
const isSubmitting = ref(false);

// 表单验证状态
const accountValid = ref(false);
const accountTouched = ref(false);
const accountError = ref('');

const emailValid = ref(false);
const emailTouched = ref(false);
const emailError = ref('');

const passwordValid = ref(false);
const passwordTouched = ref(false);
const passwordError = ref('');

// 密码相关状态
const showPassword = ref(false);
const passwordStrength = ref(0);
const passwordStrengthText = ref('未输入');
const passwordStrengthClass = ref('bg-gray-300');

// 其他状态
const showSuccessModal = ref(false);
const isScrolled = ref(false);

// 用户名验证
const validateAccount = () => {
  accountTouched.value = true;
  const account = formData.account;

  if (account.length >= 3 && account.length <= 20) {
    accountValid.value = true;
    accountError.value = '';
    return true;
  } else {
    accountValid.value = false;
    accountError.value = '用户名长度必须在3-20个字符之间';
    return false;
  }
};

// 邮箱验证
const validateEmail = () => {
  emailTouched.value = true;
  const email = formData.email;
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (emailRegex.test(email)) {
    emailValid.value = true;
    emailError.value = '';
    return true;
  } else {
    emailValid.value = false;
    emailError.value = '请输入有效的邮箱地址';
    return false;
  }
};

// 密码验证和强度检测
const validatePassword = () => {
  passwordTouched.value = true;
  const password = formData.password;
  let strength = 0;

  // 基本长度检查
  if (password.length >= 8) {
    strength += 25;
  }

  // 包含数字
  if (/\d/.test(password)) {
    strength += 25;
  }

  // 包含小写字母
  if (/[a-z]/.test(password)) {
    strength += 25;
  }

  // 包含大写字母或特殊字符
  if (/[A-Z]/.test(password) || /[^A-Za-z0-9]/.test(password)) {
    strength += 25;
  }

  // 更新强度状态
  passwordStrength.value = strength;

  // 更新强度文本和样式
  if (strength === 0) {
    passwordStrengthText.value = '未输入';
    passwordStrengthClass.value = 'bg-gray-300';
  } else if (strength <= 25) {
    passwordStrengthText.value = '弱';
    passwordStrengthClass.value = 'bg-red-500';
  } else if (strength <= 50) {
    passwordStrengthText.value = '中';
    passwordStrengthClass.value = 'bg-yellow-500';
  } else if (strength <= 75) {
    passwordStrengthText.value = '良好';
    passwordStrengthClass.value = 'bg-blue-500';
  } else {
    passwordStrengthText.value = '强';
    passwordStrengthClass.value = 'bg-green-500';
  }

  // 验证密码
  if (password.length < 8) {
    passwordValid.value = false;
    passwordError.value = '密码长度至少为8位';
    return false;
  } else if (!/\d/.test(password) || !/[a-zA-Z]/.test(password)) {
    passwordValid.value = false;
    passwordError.value = '密码必须包含字母和数字';
    return false;
  } else {
    passwordValid.value = true;
    passwordError.value = '';
    return true;
  }
};

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

// 表单提交处理
const handleSubmit = () => {
  // 触发所有验证
  const isAccountValid = validateAccount();
  const isEmailValid = validateEmail();
  const isPasswordValid = validatePassword();

  // 如果所有字段都有效
  if (isAccountValid && isEmailValid && isPasswordValid) {
    isSubmitting.value = true;
    // 这里会发送表单数据到服务器
    axios.post("/api/users/register?account="+formData.account+"&email="+formData.email+"&password="+formData.password)
        .then(res =>{
          if (res.data.code === 200){
            console.log("注册成功");
            // 注册成功，显示成功弹窗
            showSuccessModal.value = true;
            //重置表单
            resetForm();
          }
          else if (res.data.code === -201){
            console.log("用户名已存在");
            ElMessage({
              message:res.data.msg,
              type:"error",
              duration:2000,
            })
          } else {
            ElMessage({
              message:res.data.msg,
              type:"error",
              duration:2000,
            })
          }

        })
        .finally(()=>{
          isSubmitting.value = false;
        })
  }
};

// 重置表单
const resetForm = () => {
  formData.data = {
    account: '',
    email: '',
    password: ''
  };

  // 重置验证状态
  accountValid.value = false;
  accountTouched.value = false;
  emailValid.value = false;
  emailTouched.value = false;
  passwordValid.value = false;
  passwordTouched.value = false;

  // 重置密码强度
  passwordStrength.value = 0;
  passwordStrengthText.value = '未输入';
  passwordStrengthClass.value = 'bg-gray-300';
};

//跳转到登录
const goToLogin = () =>{
  router.push("/login");
}

// 关闭弹窗
const closeModal = () => {
  showSuccessModal.value = false;
};

// 监听滚动事件
onMounted(() => {
  const handleScroll = () => {
    isScrolled.value = window.scrollY > 10;
  };

  window.addEventListener('scroll', handleScroll);

  // 组件卸载时移除事件监听
  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
});
</script>

<style scoped>
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
  .bg-gradient-primary {
    background: linear-gradient(135deg, #165DFF 0%, #36BFFA 100%);
  }
  .text-shadow {
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  .transition-all-300 {
    transition: all 300ms ease-in-out;
  }
}

/* 确保Tailwind配置的样式能正确应用 */
:root {
  --color-primary: #165DFF;
  --color-secondary: #36BFFA;
  --color-neutral: #F5F7FA;
  --color-dark: #1D2129;
}

.hidden {
  display: none !important;
}
</style>
